// ///////////////////////////// MIT License //////////////////////////////////// //
//                                                                                //
// Copyright (c) 2010 David Zsolt Manrique                                        //
//                    david.zsolt.manrique@gmail.com                              //
//                                                                                //
// Permission is hereby granted, free of charge, to any person obtaining a copy   //
// of this software and associated documentation files (the "Software"), to deal  //
// in the Software without restriction, including without limitation the rights   //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      //
// copies of the Software, and to permit persons to whom the Software is          //
// furnished to do so, subject to the following conditions:                       //
//                                                                                //
// The above copyright notice and this permission notice shall be included in     //
// all copies or substantial portions of the Software.                            //
//                                                                                //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN      //
// THE SOFTWARE.                                                                  //
//                                                                                //
// ////////////////////////////////////////////////////////////////////////////// //

#include <iostream>
#include <ostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <complex>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <list>
#include <set>
#include <cstdarg>
#include <stdexcept>

#include <Eigen/Eigen>

#include <cmdioutil.h>
#include "xyz.h"


//#ifdef DEBUG
void out_complex_matrix(Eigen::Matrix< std::complex<double> , Eigen::Dynamic, Eigen::Dynamic >  m,std::ostream & os,bool comment = true,int w = 18,int p = 10)
{
        //os.flags(std::ios::scientific);
        os.flags(std::ios::fixed);
        if(comment)
        {
                os << '#';
                os << std::left << std::setw(w-1) << std::setprecision(p) << "Re Im ... Re Im" << ' '; 
                os << std::endl;
        }
        for(int i = 0; i < m.rows(); i++)
        {
	        for(int j = 0; j < m.cols(); j++)
                {
                        os << std::right << std::setw(w+4) << std::setprecision(p) << real(m(i,j)) << ' '; 
                        os << std::right << std::setw(w) << std::setprecision(p) << imag(m(i,j)) << ' '; 
                }
                os << std::endl;                        
        }                
        os << std::endl;                        
}
//#endif

#ifdef DEBUG
void out_complex_vector(Eigen::Matrix< std::complex<double> , Eigen::Dynamic, 1 >  m,std::ostream & os,bool comment = true,int w = 18,int p = 10)
{
        os.flags(std::ios::scientific);
        if(comment)
        {
                os << '#';
                os << std::left << std::setw(w-1) << std::setprecision(p) << "Re Im" << ' '; 
                os << std::endl;
        }
        for(int i = 0; i < m.rows(); i++)
        {
                        os << std::right << std::setw(w+4) << std::setprecision(p) << real(m(i)) << ' '; 
                        os << std::right << std::setw(w) << std::setprecision(p) << imag(m(i)) << ' '; 
                os << std::endl;                        
        }                
        os << std::endl;                        
}
#endif

#ifdef DEBUG
void out_real_matrix(Eigen::Matrix< double , Eigen::Dynamic, Eigen::Dynamic >  m,std::ostream & os,bool comment = true,int w = 18,int p = 10)
{
        os.flags(std::ios::scientific);
        for(int i = 0; i < m.rows(); i++)
        {
	        for(int j = 0; j < m.cols(); j++)
                {
                        os << std::right << std::setw(w+4) << std::setprecision(p) << m(i,j) << ' '; 
                }
                os << std::endl;                        
        }                
        os << std::endl;                        
}
#endif



void get_orbital_range(const std::vector<std::pair<int,int> > & range,const util::pair_expression<int,int,':'> &expr, int &io,int &no)
{
        int index1,index2,n;
        n = range.size();
        index1 = std::get<0>(expr);
        index2 = std::get<1>(expr);
        if(index1*index2 == 0) throw std::runtime_error("Index cannot be zero.");
        int i1,i2;
        i1 = index1 < 0 ? index1 + n : index1 - 1;
        i2 = index2 < 0 ? index2 + n : index2 - 1;
        if(i1 > i2) std::swap(i1,i2);                    
    
        io = range[i1].first;
        no = range[i2].second-io;
}

void get_index_list(const util::list_expression<int> &expr, int noa,std::list<int>& index_list)
{
        for(util::list_expression<int>::const_iterator it = expr.begin(); it != expr.end(); it++)
        if(*it == 0) throw std::runtime_error("Index cannot be zero in the index list.");
        else if((*it > noa) || (*it < -noa)) throw std::runtime_error("Index is out of range in the index list. There are less atoms!");
        else
        {
            int index = *it;
            int i = index < 0 ? index + noa : index - 1;
            index_list.push_back(i);
        }
}

struct blockSH
{
    std::vector<std::pair<int,int> > orbital_range;
    Eigen::MatrixXcd S,H;
    double ef;
        
    void set_orbital_range(int natom,int norb)
    {
        orbital_range.clear();
        for(int i=0; i<natom;i++)
        orbital_range.push_back(std::pair<int,int>(i*norb,norb));
        S.resize(natom*norb,natom*norb);    
        H.resize(natom*norb,natom*norb);    
        ef=0.0;
    }
    
    void get_block(int I,int J,Eigen::MatrixXcd & s,Eigen::MatrixXcd & h) const
    {
        int i,j,ni,nj;
        i = orbital_range[I].first;
        ni = orbital_range[I].second;
        j = orbital_range[J].first;
        nj = orbital_range[J].second;
        s = S.block(i,j,ni,nj);
        h = H.block(i,j,ni,nj);
    }

    void set_block(int I,int J,const Eigen::MatrixXcd & s,const Eigen::MatrixXcd & h)
    {
        int i,j,ni,nj;
        i = orbital_range[I].first;
        ni = orbital_range[I].second;
        j = orbital_range[J].first;
        nj = orbital_range[J].second;
        S.block(i,j,ni,nj) = s;
        H.block(i,j,ni,nj) = h;
    }

    void get_block(const std::list<int> & index_list_I,const std::list<int> & index_list_J,Eigen::MatrixXcd & s,Eigen::MatrixXcd & h) const
    {
        int nI,nJ;
        nI = 0;
        for(std::list<int>::const_iterator it = index_list_I.begin(); it != index_list_I.end(); it++) nI += orbital_range[*it].second;
        nJ = 0;
        for(std::list<int>::const_iterator it = index_list_J.begin(); it != index_list_J.end(); it++) nJ += orbital_range[*it].second;
    
        s.resize(nI,nJ);
        h.resize(nI,nJ);
        int li = 0;
        for(std::list<int>::const_iterator it = index_list_I.begin(); it != index_list_I.end(); it++) 
        {
            int I = *it;
            int i,ni;
            i = orbital_range[I].first;
            ni = orbital_range[I].second;
            int lj = 0;
            for(std::list<int>::const_iterator jt = index_list_J.begin(); jt != index_list_J.end(); jt++) 
            {
                int J = *jt;
                int j,nj;
                j = orbital_range[J].first;
                nj = orbital_range[J].second;
                s.block(li,lj,ni,nj) = S.block(i,j,ni,nj);
                h.block(li,lj,ni,nj) = H.block(i,j,ni,nj);
                lj += nj;
            }
            li += ni;
        }
    }

    void set_block(const std::list<int> & index_list_I,const std::list<int> & index_list_J,const Eigen::MatrixXcd & s,const Eigen::MatrixXcd & h)
    {
        int li = 0;
        for(std::list<int>::const_iterator it = index_list_I.begin(); it != index_list_I.end(); it++) 
        {
            int I = *it;
            int i,ni;
            i = orbital_range[I].first;
            ni = orbital_range[I].second;
            int lj = 0;
            for(std::list<int>::const_iterator jt = index_list_J.begin(); jt != index_list_J.end(); jt++) 
            {
                int J = *jt;
                int j,nj;
                j = orbital_range[J].first;
                nj = orbital_range[J].second;
                S.block(i,j,ni,nj) = s.block(li,lj,ni,nj);
                H.block(i,j,ni,nj) = h.block(li,lj,ni,nj);
                lj += nj;
            }
            li += ni;
        }
    }

    void print_pattern_H(std::ostream & os,double tol = 1e-6) const
    {
        for(std::vector<std::pair<int,int> >::const_iterator it = orbital_range.begin(); it != orbital_range.end(); it++) 
        {
            for(std::vector<std::pair<int,int> >::const_iterator jt = orbital_range.begin(); jt != orbital_range.end(); jt++)
            {
                int i,j,ni,nj;
                i = it->first;
                ni = it->second;
                j = jt->first;
                nj = jt->second;
                if(H.block(i,j,ni,nj).norm() > tol)  os << 'X'; else os << '.';
            }
            os << std::endl;
        }
    }
};


void load(std::string fn,blockSH & sh)
{
    std::complex<double> ii(0,1.0);
    
    std::vector<std::string> lines;
    io::load(fn,"#",lines);

    sh.ef = 0.0;
    std::vector<std::string> efermi_block;
    io::parse_block("<fermi-energy>","</fermi-energy>",lines,efermi_block);
    for(std::vector<std::string>::iterator it = efermi_block.begin(); it != efermi_block.end(); it++)
    {
        std::istringstream iss(*it);
        if (!(iss >> sh.ef)) throw std::runtime_error("Not able to parse fermi energy block in the input file!");
        break;
    }

    std::vector<std::string> orbital_block;
    if(!io::parse_block("<index-orbital>","</index-orbital>",lines,orbital_block)) throw std::runtime_error("No or inproper index-orbital block in the input file!");
    if(!orbital_block.size()) throw std::runtime_error("No or inproper index-orbital block in the input file!");
    
    sh.orbital_range.clear();
    int index,orbital;
    int inc = 0;
    int orbital_index = 0;
    for(std::vector<std::string>::iterator it = orbital_block.begin(); it != orbital_block.end(); it++)
    if(util::match("% %",*it,index,orbital))
    {
            std::pair<int,int> p(orbital_index,orbital);
            orbital_index += orbital;
            sh.orbital_range.push_back(p);
            if(++inc != index) throw std::runtime_error("Index has to be in order from 1 in the index-orbital block!");
    }
    int n = orbital_index;
    sh.H.resize(n,n); sh.H.setZero(); sh.S = sh.H; sh.S.setIdentity();
    double re,im;
    int i,j;

    std::vector<std::string> overlap_block;
    if(!io::parse_block("<overlap>","</overlap>",lines,overlap_block)) throw std::runtime_error("There is no overlap matrix block or it is inproper in the input file!");
    for(std::vector<std::string>::iterator it = overlap_block.begin(); it != overlap_block.end(); it++)
    if(util::match("% % % % ",*it,i,j,re,im)) { if((i<n+1)&&(j<n+1)&&(i>0)&&(j>0)) sh.S(i-1,j-1)=re+ii*im; else throw std::runtime_error("Inconsistent overlap matrix index with index orbital block!");  }
    else if(util::match("% % % ",*it,i,j,re)) { if((i<n+1)&&(j<n+1)&&(i>0)&&(j>0)) sh.S(i-1,j-1)=re+ii*0.0; else throw std::runtime_error("Inconsistent overlap matrix index with index orbital block!"); }
    
    std::vector<std::string> hamiltonian_block;
    if(!io::parse_block("<hamiltonian>","</hamiltonian>",lines,hamiltonian_block)) throw std::runtime_error("There is no hamiltonian block or it is inproper in the input file!");
    for(std::vector<std::string>::iterator it = hamiltonian_block.begin(); it != hamiltonian_block.end(); it++)
    if(util::match("% % % % ",*it,i,j,re,im)) { if((i<n+1)&&(j<n+1)&&(i>0)&&(j>0)) sh.H(i-1,j-1)=re+ii*im; else throw std::runtime_error("Inconsistent hamiltonian index with index orbital block!"); }
    else if(util::match("% % % ",*it,i,j,re)) { if((i<n+1)&&(j<n+1)&&(i>0)&&(j>0)) sh.H(i-1,j-1)=re+ii*0.0; else throw std::runtime_error("Inconsistent hamiltonian index with index orbital block!"); }
    if(!hamiltonian_block.size()) throw std::runtime_error("There is no hamiltonian block or it is inproper in the input file!");

}

void save(std::string fn,blockSH & sh)
{
    std::complex<double> ii(0,1.0);
    std::ofstream os(fn.c_str());
    
    os << "<fermi-energy>" << std::endl;
    os << sh.ef << std::endl;
    os << "</fermi-energy>" << std::endl;
    os << std::endl;
    os << "<index-orbital>" << std::endl;
    for(int i=0; i<sh.orbital_range.size(); i++)    
    os << i+1 << " " /*<< sh.orbital_range[i].first << " "*/ << sh.orbital_range[i].second << std::endl;
    os << "</index-orbital>" << std::endl;
    os << std::endl;
    os << "<overlap>" << std::endl;
    for(int i=0;i<sh.S.rows();i++)
    for(int j=0;j<sh.S.cols();j++)
    if(std::abs(sh.S(i,j))> 1e-4 )
    {
        os << "   " << i+1 << "    " << j+1 << "     "<< std::real(sh.S(i,j)) << "    " << std::imag(sh.S(i,j)) << std::endl;
    }
    os << "</overlap>" << std::endl;
    os << std::endl;
    os << "<hamiltonian>" << std::endl;
    for(int i=0;i<sh.H.rows();i++)
    for(int j=0;j<sh.H.cols();j++)
    if(std::abs(sh.H(i,j))> 1e-4 )
    {
        os << "   " << i+1 << "    " << j+1 << "     "<< std::real(sh.H(i,j)) << "    " << std::imag(sh.H(i,j)) << std::endl;
    }
    os << "</hamiltonian>" << std::endl;

    os.close();
    
//    std::cout << sh.H.rows() << "  " << sh.H.cols() << std::endl;
}


void load_gollum(std::string fn,blockSH & sh)
{
    std::ifstream is(fn.c_str());
    std::complex<double> ii(0,1.0);
    std::string dump;
    if(!(is >> dump >> dump >> dump >> dump >> dump >> dump >> dump)) throw std::runtime_error("Wrong gollum input format: Syntax error near the beginning!");
    if(!(is >> dump >> dump >> dump >> dump >> dump >> dump >> sh.ef )) throw std::runtime_error("Wrong gollum input format: Syntax error near the beginning!");
    if(!(is >> dump >> dump >> dump >> dump >> dump >> dump )) throw std::runtime_error("Wrong gollum input format: Syntax errour near the beginning!");
    int rows,cols; 
    if(!(is >> dump >> dump >> rows )) throw std::runtime_error("Wrong gollum input format: Syntax error near the beginning");
    if(!(is >> dump >> dump >> cols )) throw std::runtime_error("Wrong gollum input format: Syntax error near the beginning");
    int index;
    int pindex = 1;
    int pi = 0;
    int n = rows;    
    sh.orbital_range.clear();
    for(int j = 0; j < n; j++)
    {
        if(!(is >> index >> dump >> dump >> dump >> dump )) throw std::runtime_error("Wrong gollum input format: Syntax error in the orbital block!");
        if(index != pindex)
        {
            std::pair<int,int> p(pi,j-pi);
            sh.orbital_range.push_back(p);
            pindex = index;
            pi = j;
        }
    }
    std::pair<int,int> p(pi,n-pi);
    sh.orbital_range.push_back(p);

    if(!(is >> dump >> dump >> dump >> dump >> dump >> dump )) throw std::runtime_error("Wrong gollum input format: Syntax error near k-block!");
    //int rows,cols;
    if(!(is >> dump >> dump >> rows  )) throw std::runtime_error("Wrong gollum input format: Syntax error near k-block!");
    if(!(is >> dump >> dump >> cols  )) throw std::runtime_error("Wrong gollum input format: Syntax error near k-block!");
    for(int j = 0; j < rows; j++)
        if(!(is >> dump >> dump >> dump  )) throw std::runtime_error("Wrong gollum input format: Syntax error in k-block!");
    if(rows > 1) std::cerr << "Warning: Gollum input delivers multiple k point matrix. This load does not handle that, instead try separate xml inputs for each k-point." << std::endl;
    if(!(is >> dump >> dump >> dump >> dump >> dump >> dump  )) throw std::runtime_error("Wrong gollum input format: Syntax error near matrix block!");
    //int rows,cols;
    if(!(is >> dump >> dump >> rows  )) throw std::runtime_error("Wrong gollum input format: Syntax error near matrix block!");
    if(!(is >> dump >> dump >> cols  )) throw std::runtime_error("Wrong gollum input format: Syntax error near matrix block!");
    sh.H.resize(n,n); sh.H.setZero(); sh.S = sh.H;
    for(int k = 0; k < rows; k++)
    {
        int i,j;
        double res,ims,reh,imh;
        if(!(is >> dump >> i >> j >> res >> ims >> reh >> imh  )) throw std::runtime_error("Wrong gollum input format: Syntax error in matrix block!");
        sh.H(i-1,j-1)=reh+ii*imh;
        sh.S(i-1,j-1)=res+ii*ims;

    }
    is.close();
    
}

struct coupling_system : public std::map<std::tuple<int,int,int>,std::tuple<Eigen::MatrixXcd,Eigen::MatrixXcd>  >
{
    double ef;
    Eigen::Vector3d a1,a2,a3;

    bool get_sh(int i1,int i2,int i3,Eigen::MatrixXcd & s,Eigen::MatrixXcd & h)
    {
        coupling_system::iterator csit = this->find(std::make_tuple(i1,i2,i3));
        if(csit != this->end())
        {
            s = std::get<0>(csit->second);
            h = std::get<1>(csit->second);
            //h = std::get<1>((*this)[std::make_tuple(i1,i2,i3)]);
        }
        else  return false;
        return true;
    }

    void set_sh(int i1,int i2,int i3,const Eigen::MatrixXcd & s,const Eigen::MatrixXcd & h)
    {
        (*this)[std::make_tuple(i1,i2,i3)]= std::make_tuple(s,h);
    }
    
    bool check_hermiticity(double tol = 1.0e-4)
    {

        bool ch = true;
        for(coupling_system::iterator it = this->begin(); it != this->end(); it++)
        {
        
            Eigen::MatrixXcd & s = std::get<0>(it->second);
            Eigen::MatrixXcd & h = std::get<1>(it->second);
            int n1,n2,n3;
            n1 = std::get<0>(it->first);
            n2 = std::get<1>(it->first);
            n3 = std::get<2>(it->first);

            Eigen::MatrixXcd s2;
            Eigen::MatrixXcd h2;
            
            if( get_sh(-n1,-n2,-n3,s2,h2) )
            if( ((s2.adjoint()-s).norm() > tol) || ( (h2.adjoint()-h).norm() > tol)) 
            {
                std::cout << "hermiticity failed at: " << n1 << " " << n2 << " " << n3 << " s,h antisym norms are : " << (s2.adjoint()-s).norm()/s.norm() << "  " << (h2.adjoint()-h).norm()/h.norm() << std::endl;
                ch = false;
//              return false;
            }

        }
        
        return ch;


    }
};


struct lattice_system
{
    //input
    std::vector<Eigen::Vector3d> coord;
    int Iref,Ia,Ib,Ic;
    blockSH sh;
    
    //intermediate
    Eigen::Matrix3d iabc;
    std::vector<Eigen::Vector3i> nnn;
    
    //output
    Eigen::Vector3d a1,a2,a3;
    
    void setIIII(int pIref,int pIa,int pIb,int pIc)
    {
        Iref = pIref;
        Ia = pIa;
        Ib = pIb;
        Ic = pIc;

        Eigen::Matrix3d abc;
        a1 = coord[Ia]-coord[Iref];
        a2 = coord[Ib]-coord[Iref];
        a3 = coord[Ic]-coord[Iref];
        abc.col(0) = a1;
        abc.col(1) = a2;
        abc.col(2) = a3;
        iabc = abc.inverse();

        nnn.clear();
        for(std::vector<Eigen::Vector3d>::const_iterator it = coord.begin(); it != coord.end(); it++)
        {
            Eigen::Vector3d r = *it - coord[Iref];
            Eigen::Vector3i n;
            r2n(r,n);
            nnn.push_back(n);
        }
    }
    void r2n(const Eigen::Vector3d & r,Eigen::Vector3i & n) const
    {
        Eigen::Vector3d v; v = iabc*r;
        n.x() = std::round(v.x()); n.y() = std::round(v.y()); n.z() = std::round(v.z());
    }

    bool findn(const Eigen::Vector3i & n,int & I) const
    {
        for(int i = 0; i < nnn.size(); i++) if(nnn[i] == n) { I = i; return true; }
        return false;
    }

};



void save(std::string fn,coupling_system & cs)
{
    std::complex<double> ii(0,1.0);
    std::ofstream os(fn.c_str());
    
    os << "<fermi-energy>" << std::endl;
    os << cs.ef << std::endl;
    os << "</fermi-energy>" << std::endl;
    os << std::endl;

    os << "<primitive>" << std::endl;
    os << cs.a1.x() << " " << cs.a1.y() << " " << cs.a1.z() << std::endl;
    os << cs.a2.x() << " " << cs.a2.y() << " " << cs.a2.z() << std::endl;
    os << cs.a3.x() << " " << cs.a3.y() << " " << cs.a3.z() << std::endl;
    os << "</primitive>" << std::endl;
    os << std::endl;

    for(coupling_system::iterator it = cs.begin(); it != cs.end(); it++)
    {
        
        Eigen::MatrixXcd & s = std::get<0>(it->second);
        Eigen::MatrixXcd & h = std::get<1>(it->second);
        os << "<coupling>" << std::endl;
        os << "<lattice>" << std::endl;
        os << std::get<0>(it->first) << " " << std::get<1>(it->first) << " " << std::get<2>(it->first) << std::endl;
        os << "</lattice>"  << std::endl;
        os << "<overlap>" << std::endl;
        for(int i=0; i < s.rows(); i++ )
        {
            for(int j=0; j < s.cols(); j++ )
            {
                if(std::real(s(i,j)) == 0.0) os << std::right << std::setw(13) << std::setprecision(5) << "0" << ' ';
//                else if(std::abs(std::real(s(i,j))) > 1.0e-2 ) os << std::right << std::setw(13) << std::setprecision(8) << std::fixed << std::real(s(i,j)) << ' ';
                else os << std::right << std::setw(13) << std::setprecision(7) << std::scientific << std::real(s(i,j)) << ' ';

                if(std::imag(s(i,j)) == 0.0) os << std::right << std::setw(15) << std::setprecision(5) << "0" << ' ';
//                else if(std::abs(std::imag(s(i,j))) > 1.0e-2 ) os << std::right << std::setw(15) << std::setprecision(8) << std::fixed << std::imag(s(i,j)) << ' ';
                else os << std::right << std::setw(15) << std::setprecision(7) << std::scientific << std::imag(s(i,j)) << ' ';
            }
            os << std::endl;
        }
        os << "</overlap>" << std::endl;
        os << "<hamiltonian>" << std::endl;
        for(int i=0; i < h.rows(); i++ )
        {
            for(int j=0; j < h.cols(); j++ )
            {
                if(std::real(h(i,j)) == 0.0) os << std::right << std::setw(13) << std::setprecision(5) << "0" << ' ';
//                else if(std::abs(std::real(h(i,j))) > 1.0e-2 ) os << std::right << std::setw(13) << std::setprecision(8) << std::fixed << std::real(h(i,j)) << ' ';
                else os << std::right << std::setw(13) << std::setprecision(7) << std::scientific << std::real(h(i,j)) << ' ';

                if(std::imag(h(i,j)) == 0.0) os << std::right << std::setw(15) << std::setprecision(5) << "0" << ' ';
//                else if(std::abs(std::imag(h(i,j))) > 1.0e-2 ) os << std::right << std::setw(15) << std::setprecision(8) << std::fixed << std::imag(h(i,j)) << ' ';
                else os << std::right << std::setw(15) << std::setprecision(7) << std::scientific << std::imag(h(i,j)) << ' ';
            }
            os << std::endl;
        }
        os << "</hamiltonian>" << std::endl;
    
        os << "</coupling>" << std::endl;
        os << std::endl;
    }
    
    os.close();
    
}


void load(std::string fn,coupling_system & cs)
{
    std::complex<double> ii(0,1.0);
    std::vector<std::string> lines;
    io::load(fn,"#",lines);

    cs.ef = 0.0;
    std::vector<std::string> efermi_block;
    io::parse_block("<fermi-energy>","</fermi-energy>",lines,efermi_block);
    for(std::vector<std::string>::iterator it = efermi_block.begin(); it != efermi_block.end(); it++)
    {
        std::istringstream iss(*it);
        if (!(iss >> cs.ef)) throw std::runtime_error("Not able to parse fermi energy block in the input file!");
        break;
    }
    
    
    double ax,ay,az; int a123 = 0;
    std::vector<std::string> primitive_block;
    if(!io::parse_block("<primitive>","</primitive>",lines,primitive_block)) throw std::runtime_error("No or inproper primitive block in the input file!");
    if(!primitive_block.size()) throw std::runtime_error("No or inproper primitive block in the input file!");
    for(std::vector<std::string>::iterator it = primitive_block.begin(); it != primitive_block.end(); it++)
    if(util::match("% % %",*it,ax,ay,az))
    {
        a123++;
        if(a123 == 1) cs.a1 << ax,ay,az; 
        if(a123 == 2) cs.a2 << ax,ay,az; 
        if(a123 == 3) cs.a3 << ax,ay,az; 
    }



    std::vector<std::vector<std::string> >  coupling_blocks;
    if(!io::parse_block("<coupling>","</coupling>",lines,coupling_blocks)) throw std::runtime_error("No or inproper coupling block in the input file!");
    if(!primitive_block.size()) throw std::runtime_error("No or inproper coupling block in the input file!");
    for(std::vector<std::vector<std::string>>::iterator bit = coupling_blocks.begin(); bit != coupling_blocks.end(); bit++)
//    for(std::vector<std::string>::iterator it = bit->begin(); it != bit->end(); it++)
    {

        std::vector<std::string> block;
        int n1,n2,n3;
        if(!io::parse_block("<lattice>","</lattice>",*bit,block)) throw std::runtime_error("No or inproper lattice block in the input file!");
        if(!block.size()) throw std::runtime_error("No or inproper lattice block in the input file!");
        for(std::vector<std::string>::iterator it = block.begin(); it != block.end(); it++)
        if(util::match("% % %",*it,n1,n2,n3)) break;

        Eigen::MatrixXcd s,h;
        if(!io::parse_block("<overlap>","</overlap>",*bit,block)) throw std::runtime_error("No or inproper overlap block in the input file!");
        if(!block.size()) throw std::runtime_error("No or inproper overlap block in the input file!");
        int rows = block.size();
        int cols = 0;
        { std::istringstream iss(block[0]); double re,im; while(iss>>re>>im) { cols++; } }
        s.resize(rows,cols);
        for(int i = 0; i < rows; i++)
        {
            std::istringstream iss(block[i]); int j = 0;  double re,im;  while(iss>>re>>im) { s(i,j)=re+ii*im; j++; }
        }

        if(!io::parse_block("<hamiltonian>","</hamiltonian>",*bit,block)) throw std::runtime_error("No or inproper hamiltonian block in the input file!");
        if(!block.size()) throw std::runtime_error("No or inproper hamiltonian block in the input file!");
        rows = block.size();
        cols = 0;
        { std::istringstream iss(block[0]); double re,im; while(iss>>re>>im) { cols++; } }
        h.resize(rows,cols);
        for(int i = 0; i < rows; i++)
        {
            std::istringstream iss(block[i]); int j = 0;  double re,im;  while(iss>>re>>im) { h(i,j)=re+ii*im; j++; }
        }
        
        cs.set_sh(n1,n2,n3,s,h);

    }
    
}




void get_cmd(int argc, char* argv[],coupling_system & cs,std::string & out)
{
        cmd::arguments arg(argc,argv);
        cmd::switcharg<false> help(arg,"-h","--help", "print help message");
        cmd::switcharg<false> info(arg,"-i","--info", "print info/example message");

        cmd::varargxxxx<int,int,int,int> iiii(arg,"-iiii","--iiii","iref ia ib ic",1,2,3,4);             

        cmd::posarg<std::string> ham_fn(arg,"input hamiltonian file name", "");
        cmd::posarg<std::string> xyz_fn(arg,"input xyz file name", "");
        cmd::posarg<std::string> out_fn(arg,"outpu file name", "");

        if(*help)
        {
                arg.print_help(std::cout,"lattice_coupling");
                std::cout << "examples:" << std::endl;
                std::cout << "version 0.9b" << std::endl;
                exit(EXIT_SUCCESS);
        }
        if(*info)
        {
                std::cout << "version 0.9b" << std::endl;
                std::cout << "Copyright (c) 2010 David Zsolt Manrique (david.zsolt.manrique@gmail.com)"  << std::endl;
                //return EXIT_SUCCESS;
                exit(EXIT_SUCCESS);
        }                                                                                                                


        if(!~xyz_fn) throw std::runtime_error("Give reference structure file!");
        if(!~ham_fn) throw std::runtime_error("Give reference hamiltonian file!");
        if(!~iiii) throw std::runtime_error("Give reference atom and lattice neighbours index!");
        
        xyz c;
        load(*xyz_fn,c);
        blockSH sh;
        load(*ham_fn,sh);
        
        lattice_system ls;
        ls.sh = sh;
        ls.coord = c.coords;
        ls.setIIII(iiii.var1,iiii.var2,iiii.var3,iiii.var4);
        
        cs.a1 = ls.a1;
        cs.a2 = ls.a2;
        cs.a3 = ls.a3;
                
        cs.ef = ls.sh.ef;
        for(int i=0; i < ls.nnn.size(); i++)
        {
            Eigen::MatrixXcd s,h;
            ls.sh.get_block(ls.Iref,i,s,h);
            cs.set_sh(ls.nnn[i].x(),ls.nnn[i].y(),ls.nnn[i].z(),s,h);
        }
                
        out = *out_fn;

}



using namespace std;


int main(int argc, char* argv[])
{
try
{
    coupling_system cs,cs1;
    
    std::string outfn;
    get_cmd(argc,argv,cs,outfn);
    save(outfn,cs);
    
    cs.check_hermiticity();
        
    //load("cs.cs",cs1);
    
    //save("cs1.cs",cs1);
    
    
    
} catch(const char* message)
{
    std::cerr << message << std::endl;
    std::cerr << "(exit)" << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    std::cerr << "(exit)" << std::endl;
    return EXIT_FAILURE;
}
    return EXIT_SUCCESS;



}


/*
int main(int argc, char* argv[])
{
try
{
         rH,rS,H,S;
        
        std::vector<Eigen::Vector3d> rc,c; 
        std::vector<std::pair<int,int> > ror;
        double ref;
        
        get_cmd(argc,argv,rc,ror,rh,rs,ref,c);
        
        Eigen::MatirxXi rh,rk,rl,h,k,l;
        Eigen::Vector3d a1,a2,a3;
        structure_hkl(rc,a1,a2,a3,rh,rk,rl);
        structure_hkl(c,a1,a2,a3,h,k,l);
        
        int rn,n;
        rn = rc.size();
        n = c.size();
    
        //> fast solution
        Eigen::MatrixXcd Hblock,Sblock;
        get_atomic_block_IJ(rH,ror,0,0,Hblock);
        H.resize(n*Hblock.rows(),n*Hblock.cols());
        S.resize(n*Hblock.rows(),n*Hblock.cols());
        H.setZero();
        S.setZero();
        
        //< end
            
        for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
        {
            int h_ = h(i,j);
            int k_ = k(i,j);
            int l_ = l(i,j);
            
            bool found = false;
            for(int ri=0; ri<rn; ri++)
            for(int rj=0; rj<rn; rj++)
            if( (h_ == rh(ir,rj))  && (k_ == rk(ir,rj)) && (l_ == rl(ir,rj)) )
            {
                get_atomic_block_IJ(rH,ror,ri,rj,Hblock);
                get_atomic_block_IJ(rS,ror,ri,rj,Sblock);
                found = true;
                break;
            }
            
            if(!found)
            {
                Hblock.setZero();
                Sblock.setZero();
            }
            
            H.block(i*Hblock.rows(),j*Hblock.cols(),Hblock.rows(),Hblock.cols()) = Hblock;
            S.block(i*Hblock.rows(),j*Hblock.cols(),Hblock.rows(),Hblock.cols()) = Sblock;
        
        }

        
} catch(const char* message)
{
    std::cerr << message << std::endl;
    std::cerr << "(exit)" << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    std::cerr << "(exit)" << std::endl;
    return EXIT_FAILURE;
}
    return EXIT_SUCCESS;



}

void coord2nnn(const std::vector<Eigen::Vector3d> & coord,int Iref,int Ia,int Ib,int Ic,std::vector<Eigen::Vector3i> & nnn)
{
    Eigen::Vector3d rref = coord[Iref];
    Eigen::Matrix3d iabc,abc;
    abc.col(0) = coord[Ia]-rref;
    abc.col(1) = coord[Ib]-rref;
    abc.col(2) = coord[Ic]-rref;
    iabc = abc.inverse();

    nnn.clear();
    for(std::vector<Eigen::Vector3d>::const_iterator it = coord.begin(); it != coord.end(); it++)
    {
        Eigen::Vector3i n;
        Eigen::Vector3d r = *it - rref;
        r2n(iabc,r,n);
        nnn.push_back(n);
    }
    
}






void test(const std::vector<Eigen::Vector3d> & coord_model,
          int Iref_model,int Ia_model,int Ib_model,int Ic_model,
          const Eigen::Vector3d & A1,const Eigen::Vector3d & A2,
          const std::list<int> & atom_index_model,
          const std::vector<std::pair<int,int> > & orbital_range_model,
          Eigen::MatrixXcd & H_model,Eigen::MatrixXcd & S_model,
          
          const std::vector<Eigen::Vector3d> & coord_lattice,
          int Iref_lattice,int Ia_lattice,int Ib_lattice,int Ic_lattice,
          const std::vector<std::pair<int,int> > & orbital_range_lattice,
          const Eigen::MatrixXcd & H_lattice,const Eigen::MatrixXcd & S_lattice,
          double rcutoff)
{
    Eigen::Matrix3d iabc_lattice,abc_lattice;
    abc_lattice.col(0) = coord_lattice[Ia_lattice]-coord_lattice[Iref_lattice];
    abc_lattice.col(1) = coord_lattice[Ib_lattice]-coord_lattice[Iref_lattice];
    abc_lattice.col(2) = coord_lattice[Ic_lattice]-coord_lattice[Iref_lattice];
    iabc_lattice = abc_lattice.inverse();
    
    std::vector<Eigen::Vector3i> nnn_lattice;
    for(std::vector<Eigen::Vector3d>::const_iterator it = coord_lattice.begin(); it != coord_lattice.end(); it++)
    {
        Eigen::Vector3d r = *it - coord_lattice[Iref_lattice];
        if(r.norm() < rcutoff)
        {
            Eigen::Vector3i n;
            r2n(iabc_lattice,r,n);
            nnn_lattice.push_back(n);
        }
    }



    Eigen::Matrix3d iabc_model,abc_model;
    abc_model.col(0) = coord_model[Ia_model]-coord_model[Iref_model];;
    abc_model.col(1) = coord_model[Ib_model]-coord_model[Iref_model];;
    abc_model.col(2) = coord_model[Ic_model]-coord_model[Iref_model];;
    iabc_model = abc_model.inverse();
    for(std::list<int>::const_iterator it = atom_index_model.begin(); it != atom_index_model.end(); it++)
    {
        for(double m1 = -1.0; m1 <= 1.0; m1++) 
        for(double m2 = -1.0; m2 <= 1.0; m2++) 
        {
            Eigen::Vector3d s = m1*A1 + m2*A2;
                for(std::list<int>::const_iterator jt = atom_index_model.begin(); jt != atom_index_model.end(); jt++)
            {
                Eigen::Vector3d r = coord_model[*jt]+s - coord_model[*it];
                if(r.norm() < rcutoff)
                {
                    Eigen::Vector3i n;
                    r2n(iabc_model,r,n);
                    int J;
                    if(findnnn(nnn_lattice,n,J))
                    {
//                        H_model[*it,*jt] = H_lattice[Iref_lattice,J];
//                        S_model[*it,*jt] = S_lattice[Iref_lattice,J];
                    } else
                    {
//                        H_model[*it,*jt] = 0;
//                        S_model[*it,*jt] = 0;
                    }
                }
            }
        }
    }
    
    
    
}




*/

